﻿using AppTemplate.UI.Framework;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using Microsoft.Extensions.Configuration;
using System.Reflection;
using AppTemplate.Infrastructure.DependencyInjection;
using AppTemplate.UI.Sys;
using System.Windows.Controls;

namespace AppTemplate.UI.ViewModels
{
    [Inject(Ignored = true)]
    public partial class AppState : ViewModel
    {
        private AppState() { }
        private readonly static AppState instance = new();
        public static AppState Instance => instance;

        private IConfiguration configuration;
        public IConfiguration Configuration => configuration;

        private Stack<UserControl> PageStack = new Stack<UserControl>();

        [ObservableProperty]
        private string name;

        [ObservableProperty]
        private string? title;

        [ObservableProperty]
        private Visual? currentView;

        [ObservableProperty]
        private Visibility statusBarVisibility = Visibility.Collapsed;

        [ObservableProperty]
        private Visibility progressBarVisibility = Visibility.Collapsed;


        [ObservableProperty]
        private string? status;

        [ObservableProperty]
        private bool progressBarIsIndeterminate = true;

        [ObservableProperty]
        private double progressMaximum = 100;

        [ObservableProperty]
        private double progressValue;


        [ObservableProperty]
        private double statusBarHeight;

        [ObservableProperty]
        private string icon;

        [ObservableProperty]
        private string version;

        [ObservableProperty]
        private string appInfo;

        [ObservableProperty]
        private double width;

        [ObservableProperty]
        private double height;

        public static void Init(IConfiguration configuration)
        {
            Instance.configuration = configuration;

            Instance.Icon = GetAppSetting("App:Icon", "pack://siteoforigin:,,,/Assets/icon.jpg");
            Instance.StatusBarHeight = GetAppSetting("App:StatusBarHeight", 25);
            Instance.Name = GetAppSetting("App:Name", "未命名");
            Instance.Version = GetAppSetting("App:Version", Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? string.Empty);

            Instance.Width= GetAppSetting("App:Width", 800d);
            Instance.Height= GetAppSetting("App:Height", 800d);
        }

        private static T GetAppSetting<T>(string key, T defaultValue)
        {
            var setion = Instance.Configuration.GetSection(key);
            if (setion != null)
            {
                return setion.Get<T>() ?? defaultValue;
            }
            else return defaultValue;
        }

        public void Go<TView>(string? title = default, bool openNew = default) where TView : UserControl
        {
            var type = typeof(TView);
            TView? view = null;
            if (openNew)
            {
                view = CreateNewView<TView>(type, title);
                PageStack.Push(view);
            }
            else
            {
                bool found = TryFindView(type, out view);
                if (!found)
                {
                    view = CreateNewView<TView>(type, title);
                    PageStack.Push(view);
                }
            }

            SetCurrentView(view);
        }

        private void SetCurrentView<TView>(TView? view) where TView : UserControl
        {
            CurrentView = view;
        }

        public void Back()
        {
            PageStack.Pop();
            var d= PageStack.Peek();
            if (true)
            {
                SetCurrentView(d);
            }
            
        }

        private TView CreateNewView<TView>(Type type, string? title) where TView : UserControl
        {
            TView view = DI.Resolve<TView>();
            var viewAttr = type.GetCustomAttribute<ViewAttribute>();
            if (viewAttr != null)
            {
                var viewModel = DI.Resolve(viewAttr.ViewModelType);
                if (title != null)
                {
                    SetTitle(title);
                }
                else if (viewAttr.Title != null)
                {
                    SetTitle(viewAttr.Title);
                }
                view.DataContext = viewModel;
            }
            else
            {
                //todo:自动搜索
            }

            return view;
        }

        private bool TryFindView<TView>(Type type, out TView? view) where TView : UserControl
        {
            view = null;
            var previousView = PageStack.FirstOrDefault(p => p.GetType() == type);
            if (previousView != null)
            {
                view = previousView as TView;
                return true;
            }
            else return false;
        }

        public void SetTitle(string title, bool hideAppName = false)
        {
            Title = $"{title}{(hideAppName ? null : $"-{Name}")}";
        }

        public void ShowStatusBar(bool isShown)
        {
            if (isShown && StatusBarVisibility != Visibility.Visible)
            {
                StatusBarVisibility = Visibility.Visible;
            }
            else if (!isShown && StatusBarVisibility == Visibility.Visible)
            {
                StatusBarVisibility = Visibility.Collapsed;
            }
        }

        public void SetStatus(string? status)
        {
            ShowStatusBar(true);
            Status = status;
        }

        public void ReportProgress(double value, double maximum)
        {
            ShowProgressBar(true);
            if (ProgressBarIsIndeterminate == true)
            {
                ProgressBarIsIndeterminate = false;
            }
            if (ProgressMaximum != maximum)
            {
                ProgressMaximum = maximum;
            }

            ProgressValue = value;
        }




        private void ShowProgressBar(bool isShown)
        {
            if (isShown && ProgressBarVisibility != Visibility.Visible)
            {
                ProgressBarVisibility = Visibility.Visible;
            }
            else if (!isShown && ProgressBarVisibility == Visibility.Visible)
            {
                ProgressBarVisibility = Visibility.Collapsed;
            }
        }



        public void ShowProgress(bool progressBarIndeterminate, string? status = default)
        {
            if (status != default)
            {
                SetStatus(status);
            }
            ProgressBarIsIndeterminate = progressBarIndeterminate;
            ShowProgressBar(true);
        }


        public void HideProgress()
        {
            ShowProgressBar(false);
            SetStatus(null);
        }



        public MessageBoxResult Confirm(string message, string? caption = default, MessageBoxButton button = MessageBoxButton.OKCancel, MessageBoxImage? icon = null)
        {
            return MessageBox.Show(Application.Current.MainWindow, message, caption ?? "确认", button, (icon == null ? MessageBoxImage.None : icon.Value));
        }

        public MessageBoxResult Alert(string message, string? caption = default, MessageBoxImage icon = MessageBoxImage.None)
        {
            return MessageBox.Show(Application.Current.MainWindow, message, caption ?? "提示", MessageBoxButton.OK, icon);
        }


    }
}
